package com.swu.pad.assignment.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.swu.pad.assignment.dao.AssignmentDao;
import com.swu.pad.assignment.dao.AssignmentPadDao;
import com.swu.pad.assignment.entity.AsmtDocumentTptItem;
import com.swu.pad.assignment.entity.Assignment;
import com.swu.pad.assignment.entity.AssignmentDocumentTpt;
import com.swu.pad.assignment.entity.AssignmentPad;
import com.swu.pad.assignment.service.AssignmentPadService;
import com.swu.pad.assignment.service.AssignmentService;
import com.swu.pad.course.entity.CourseGroupUser;
import com.swu.pad.course.entity.Group;
import com.swu.pad.reflection.dao.RftDimTipsDao;
import com.swu.pad.reflection.entity.RftDimTips;
import com.swu.pad.reflection.entity.RftFeedbackItem;
import com.swu.pad.system.dto.ResultDto;
import com.swu.pad.system.entity.HelpDocument;
import com.swu.pad.system.entity.User;
import com.swu.pad.util.CookieUtil;

@Controller
@RequestMapping(value = "/assignment")
public class AssignmentController {

	@Autowired
	private AssignmentService assignmentService;
    
	@Autowired
	private AssignmentPadService assignmentPadService;
	@Autowired
	private AssignmentPadDao asPdao;
	@Autowired
	private AssignmentDao asDao;
	@Autowired
	private RftDimTipsDao rftDimTipsDao;
	/**
	 * 返回该组的行为图数据
	 * @param groupName
	 * @return
	 */
	

	@ResponseBody
	@RequestMapping(value = "/createAssignment")
	public String createAssignment(Assignment assignment) {
		
		assignmentService.addAssignment(assignment);
		return "success";
	}
	
    //创建 作业目录
	@ResponseBody
	@RequestMapping(value = "/saveAsmtDocumentTpt")
	public String saveAsmtDocumentTpt(AssignmentDocumentTpt asmtDocumentTpt) {
		assignmentService.saveAsmtDocumentTpt(asmtDocumentTpt);
		return "success";
	}
	  // 根据作业id 获取 本次作业所有关联文档
	@ResponseBody
	@RequestMapping(value = "/getAsmtDocuments")
	public List<AsmtDocumentTptItem> getAsmtDocuments(String assignmentId) {
		return assignmentService.getAsmtDocuments(assignmentId);
	}
	
	@ResponseBody
	@RequestMapping(value = "/getAsmtDocumentTpts")
	public List<AssignmentDocumentTpt> getAsmtDocumentTpts() {
		return assignmentService.getAsmtDocumentTpts();
	}
	
	 //创建 作业目录
	@ResponseBody
	@RequestMapping(value = "/deleteAsmtDocumentTpt")
	public String deleteAsmtDocumentTpt(String templateId) {
		assignmentService.deleteAsmtDocumentTpt(templateId);
		return "success";
	}
	
	 //创建 作业文档
	@ResponseBody
	@RequestMapping(value = "/saveAsmtDocumentTptItem",method=RequestMethod.POST)
	public String saveAsmtDocumentTptIteme(AsmtDocumentTptItem asmtDocumentTptItem,HttpServletRequest request,@RequestParam("document") MultipartFile document) throws Exception {
		if(document!=null){
		    Map<String,Object> map=new HashMap<String, Object>();
			//图片上传成功后，将图片的地址写到数据库
			String filePath = "c:\\padFile\\upload\\helpFile\\";
			//上传文件原始名称
			asmtDocumentTptItem.setDocumentPath(filePath);//封装路径
			String originalFilename = document.getOriginalFilename();
			asmtDocumentTptItem.setOriginalname(originalFilename);
			//新的文件
			String newFileName = originalFilename.substring(0,originalFilename.lastIndexOf("."))+UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexOf("."));
			asmtDocumentTptItem.setDocumentName(newFileName);
			File file = new java.io.File(filePath+newFileName);
			//将内存中的文件写入磁盘
			document.transferTo(file); 
		}
		assignmentService.saveAsmtDocumentTptItem(asmtDocumentTptItem);
		return "success";
	}
	
    
	/**
	 * 删除反思写作 反馈 条目
	 * @param templateId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteAsmtDocumentTptItem")
	public String deleteAsmtDocumentTptItem(String itemId) {
		assignmentService.deleteAsmtDocumentTptItem(itemId);
		return "success";
	}
	
	
	/**
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getAsmtDocumentTptItems")
	public List<AsmtDocumentTptItem> getAsmtDocumentTptItems(String templateId) {
		   return  assignmentService.getAsmtDocumentTptItems(templateId);
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/updateAssignment")
	public String updateAssignment(Assignment assignment) {
		assignmentService.updateAssignment(assignment);
		return "success";
	}

	@ResponseBody
	@RequestMapping(value = "/deleteAssignment")
	public String deleteAssignment(String assignmentId) {
		assignmentService.deleteAssignment(assignmentId);
		return "success";
	}

	@ResponseBody
	@RequestMapping(value = "/getAssignments")
	public List<Assignment> getAssignments(String courseId) {
		return assignmentService.getAssignmentByCourseId(courseId);
	}

	@ResponseBody
	@RequestMapping(value = "/getAssignment")
	public Assignment getAssignment(String assignmentId) {
		return assignmentService.getAssignment(assignmentId);
	}

	@ResponseBody
	@RequestMapping(value = "/getAssignmentDetail")
	public Map<String, Object> getAssignmentDetail(String assignmentId) {
		return assignmentService.getAssignmentDetail(assignmentId);
	}

	@ResponseBody
	@RequestMapping(value = "/getAssignmentPadId")
	public AssignmentPad getAssignmentPadId(String assignmentId, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
		User user = (User) session.getAttribute("user");
		if (User.ROLE_STUDENT.equals(user.getRole())) {
			CourseGroupUser courseGroupUser = assignmentService.getUserAssignmentSession(assignmentId, user.getId());
			Cookie cookie = CookieUtil.getCookieByName(request, "sessionID");
			if (null == cookie) {
				cookie = new Cookie("sessionID", courseGroupUser.getId());
				cookie.setPath("/");
				cookie.setMaxAge(60 * 60);// 设置为60min
				response.addCookie(cookie);
			} else {
				cookie.setValue(courseGroupUser.getId());
				cookie.setPath("/");
				cookie.setMaxAge(60 * 60);// 设置为30min
				response.addCookie(cookie);
			}
			return assignmentService.getUserAssignmentPad(assignmentId, courseGroupUser.getGroupId());
		} else {
			return null;
		}
	}

	@ResponseBody
	@RequestMapping(value = "/getAssignmentPadCurrentId")
	public Map<String, Object> getAssignmentPadCurrentId(String assignmentId, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
		User user = (User) session.getAttribute("user");
		if (User.ROLE_STUDENT.equals(user.getRole())) {
			//调用service层方法，每次进入edit页面都会执行
			CourseGroupUser courseGroupUser = assignmentService.getUserAssignmentSession(assignmentId, user.getId());
			Cookie cookie = CookieUtil.getCookieByName(request, "sessionID");
			if (null == cookie) {
				cookie = new Cookie("sessionID", courseGroupUser.getId());
				cookie.setPath("/");
				cookie.setMaxAge(60 * 60);// 设置为60min
				response.addCookie(cookie);
			} else {
				cookie.setValue(courseGroupUser.getId());
				cookie.setPath("/");
				cookie.setMaxAge(60 * 60);// 设置为30min
				response.addCookie(cookie);
			}
			Map<String, Object> map = new HashMap<String, Object>();
			String aspID=assignmentService.getAssignmentPadCurrentId(assignmentId, courseGroupUser.getGroupId());
			map.put("id",aspID);
			//反思新加 ， 需要 作业的反思写作提示语模板id - 模板的所有项目   ，返回到前台 显示在页面左边，注意检查右边的 得分
			String asType=asDao.findOne(assignmentId).getAssignmentType();
			Assignment assignment=asDao.findOne(assignmentId);
			String templateId=assignment.getRftDimTipTptId();
			List<RftDimTips> rftDimTips=rftDimTipsDao.findByTemplateId(templateId);//获取所有维度 提示语
            map.put("rftDimTips",rftDimTips);
            map.put("asType",asType);
			return map;
		} else {
			return null;
		}
	}

	@ResponseBody
	@RequestMapping(value = "/getCommentAssignmentPad")
	public Map<String, Object> getCommentAssignmentPad(String activityId, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
		User user = (User) session.getAttribute("user");
		if (User.ROLE_STUDENT.equals(user.getRole())) {
			return assignmentService.getCommentAssignmentPad(activityId, user.getId());
		} else {
			return null;
		}
	}
	@ResponseBody
	@RequestMapping(value = "/getAssignmentGroup")
	public List<Group> getAssignmentGroup(String assignmentId, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
		return assignmentService.getAssignmentGroup(assignmentId);
	}
	@ResponseBody
	@RequestMapping(value = "/replacePad")
	public ResultDto replacePad(String assignmentId, String groupId, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
		ResultDto result = new ResultDto();
		try{
			assignmentService.replacePad(assignmentId,groupId);
			result.setCode(ResultDto.CODE_OK);
		}catch(Exception e){
			result.setCode(ResultDto.CODE_INTERNAL_ERROR);
		}
		return result;
	}
}
